package com.sduept.nwld.dataserver.manager.statistics;

import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.model.countanalyse.CountProtectDefect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProtectDefectsManager {

	@Autowired
	private SuperDAO dao;

	public CountProtectDefect create(CountProtectDefect countProtectDefect) {
		return dao.createOrUpdate(countProtectDefect, CountProtectDefect.class);
	}
	
	public void delete(String id) {
		dao.delete(id, CountProtectDefect.class);
	}
	
	public List<Integer> getAllYears() {
		List<Integer> years = new ArrayList<Integer>();
		List<String> syears = (List<String>) dao.nativeQuery("select DISTINCT mid(occur_date,1,4) as year from t_count_protect_defect where occur_date !='null' order by occur_date desc");
		for (String s : syears) {
			years.add(Integer.parseInt(s));
		}
		return years;
	}
	
	public List<String> getAllProvince() {
		return (List<String>) dao.nativeQuery("select DISTINCT province from t_count_protect_defect");
	}
	
	public List<String> getAllDefectLevels() {
		return (List<String>) dao.nativeQuery("select DISTINCT defect_level from t_count_protect_defect order by defect_level");
	}
	
	public List<CountProtectDefect> query(int year,String province,String defectLevel,boolean solved) {
		return findCountProtectDefectByCondition(year, province, defectLevel, solved,null,null,null);
	}
	
	/**
	 * 按条件查询保护缺陷
	 * @param year
	 * @param province
	 * @param defectLevel
	 * @param solved
	 * @param defectDevice
	 * @param defectPosition
	 * @param defectType
	 * @return
	 */
	private List<CountProtectDefect> findCountProtectDefectByCondition(int year,String province,String defectLevel, boolean solved, String defectDevice, String defectPosition, String defectType){
		String sql = " solved is ? ";
		List<Object> values = new ArrayList<>();
		values.add(solved);
		if(year != 0) {
			sql += "and occur_date like ?";
			values.add(year+"%");
		} 
		if(!"0".equals(province)) {
			sql += " and province = ? ";
			values.add(province);
		}
		if(!"0".equals(defectLevel)) {
			sql += " and defect_Level = ? ";
			values.add(defectLevel);
		}
		if(defectDevice != null) {
			sql += " and defect_device = ?";
			values.add(defectDevice);
		}
		if(defectPosition != null) {
			sql += " and defect_position = ?";
			values.add(defectPosition);
		}
		if(defectType != null) {
			sql += " and defect_type = ?";
			values.add(defectType);
		}
		sql += " order by occur_date";
		List<CountProtectDefect> fs = dao.findByCondition(CountProtectDefect.class, sql, values.toArray());
		return fs;
	}
	
	
	
	
	public List<CountProtectDefect> findAllCountProtectDefect() {
		return dao.findAll(CountProtectDefect.class);
	}
}
